<template>
  <form @submit.prevent="submitForm">
    <div class="form-group">
      <label>用户名</label>
      <input v-model="formData.username" type="text" required>
    </div>

    <div class="form-group">
      <label>密码</label>
      <input v-model="formData.password" type="password" required>
    </div>

    <div v-if="showEmail" class="form-group">
      <label>邮箱</label>
      <input v-model="formData.email" type="email" required>
    </div>

    <button type="submit">{{ submitText }}</button>
    <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
    <p v-if="successMessage" class="success">{{ successMessage }}</p>
  </form>
</template>

<script>
export default {
  props: {
    submitText: {
      type: String,
      default: '提交'
    },
    showEmail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        username: '',
        password: '',
        email: ''
      },
      errorMessage: '',
      successMessage: ''
    }
  },
  methods: {
    async submitForm() {
      this.errorMessage = ''
      this.successMessage = ''

      try {
        let response
        if (this.showEmail) {
          response = await this.$store.dispatch('auth/register', this.formData)
        } else {
          response = await this.$store.dispatch('auth/login', this.formData)
        }

        if (response.success) {
          this.successMessage = response.message
          this.$emit('success', response)
        } else {
          this.errorMessage = response.message
        }
      } catch (error) {
        this.errorMessage = '请求失败，请稍后重试'
      }
    }
  }
}
</script>

<style scoped>
.form-group {
  margin-bottom: 1rem;
}
.error {
  color: red;
}
.success {
  color: green;
}
</style>